package com.bayi.storage.utils;

import android.os.Handler;
import android.os.Looper;

import com.bayi.storage.actions.Action;
import com.bayi.storage.actions.Action1;
import com.bayi.storage.actions.Action2;

/**
 * Created by guoping on 16/5/20.
 */
public class ThreadUtil {

    private static Handler handler = new Handler(Looper.getMainLooper());

    public static void runOnUI(Runnable runnable) {
        if (runnable == null) {
            return;
        }
        if (isUIThread()) {
            runnable.run();
        } else {
            handler.post(runnable);
        }
    }

    public static void runOnUI(Runnable runnable, int delay) {
        if (runnable == null) {
            return;
        }
        handler.postDelayed(runnable, delay);
    }

    public static void runOnUI(final Action runnable) {
        if (runnable == null) {
            return;
        }
        runOnUI(new Runnable() {
            @Override
            public void run() {
                runnable.run();
            }
        });
    }

    public static <T> void runOnUI(final Action1<T> runnable, final T arg) {
        if (runnable == null) {
            return;
        }
        runOnUI(new Runnable() {
            @Override
            public void run() {
                runnable.run(arg);
            }
        });
    }

    public static <T, T1> void runOnUI(final Action2<T, T1> runnable, final T arg, final T1 arg1) {
        if (runnable == null) {
            return;
        }
        runOnUI(new Runnable() {
            @Override
            public void run() {
                runnable.run(arg, arg1);
            }
        });
    }

    public static boolean isUIThread() {
        return Thread.currentThread().getId() == Looper.getMainLooper().getThread().getId();
    }
}
